package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品，同时插入菜品对应的口味数据，需要操作两张表：dish、dish_flavor
     * @param dishDTO
     */
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO,dish);

        //向dish表中插入一条数据
        dishMapper.insert(dish);

        //获得插入的菜品id
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            //为每条口味数据设置菜品id
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            //向dish_flavor表中插入n条数据
            dishFlavorMapper.insertBatchFlavor(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //查询结果
        Page<DishVO> dishPage = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(dishPage.getTotal(),dishPage.getResult());
    }

    /**
     * 根据id批量删除菜品信息和对应的口味信息
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断菜品是否能够被删除---菜品是否存在起售状态
        ids.forEach(id -> {
            Dish dish = dishMapper.getDishById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //菜品存在起售状态，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //判断菜品是否能够被删除---菜品是否与套餐相关联
        //查询关联表，根据dishId查询setmealId。 select setmeal_id from setmeal_dish where dish_id in (1,2,3)
        List<Long> setmealIds = setmealDishMapper.getSetmealByDishId(ids);
        if (setmealIds != null && setmealIds.size() > 0){
            //菜品与套餐关联，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品信息
        /*for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除菜品对应的口味信息
            dishFlavorMapper.deleteByDishId(id);
        }*/

        //删除菜品，口味优化  ---若数据很多将会对数据库造成压力---批量删除
        //批量删除菜品  delete from dish where id in (1,2,3)
        dishMapper.deleteByIds(ids);
        //批量删除口味  delete from dish_flavor where id in (1,2,3)
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据分类id查询菜品
     * @param dish
     */
    public List<Dish> getDishByCategoryId(Dish dish) {
        List<Dish> dishes = dishMapper.getDishByCategoryId(dish);
        return dishes;
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @Transactional
    public DishVO getByIdWithFlavor(Long id) {

        DishVO dishVO = dishMapper.getByIdWithFlavor(id);
        //查询口味
        List<DishFlavor> flavors = dishFlavorMapper.getFlavorByDishId(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 更新菜品起售状态
     * @param dish
     */
    public void updateStatus(Dish dish) {
        //todo  起售套餐中包含的菜品不能停售
        //update dish set status = ? where id = ?  这里用动态dql处理dish修改
        dishMapper.updateDish(dish);

    }

    /**
     * 更新菜品信息，同时更新菜品对应的口味信息
     * @param dishDTO
     */
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);

        //更新口味信息
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(item ->{
            item.setDishId(dishDTO.getId());
        });

        dishFlavorMapper.insertBatchFlavor(flavors);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Transactional
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getDishByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
